<?php

namespace App\Admin\Controllers\Posts;

use App\Admin\Actions\Extensions\Posts\CommentManualButton;
use App\Admin\Actions\Grid\PostCommentLotteryAction;
use App\Admin\Actions\Grid\PostMetaAction;
use App\Admin\Actions\Grid\PostPassAction;
use App\Admin\Actions\Grid\PostsAction;
use App\Admin\Actions\Grid\PostTopAction;
use App\Admin\Actions\Grid\PostUnTopAction;
use App\Admin\Actions\Grid\PostPushAction;
use App\Admin\Actions\Grid\PostShelvesAction;
use App\Admin\Repositories\Posts\WxPost;

use App\Jobs\Posts\UpdatePostOnlyTextJob;
use App\Jobs\UpdatePostImgCountJob;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\Utils;
use App\Models\Posts\WxPostsAddress;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\Posts\WxTag;
use App\Models\Circle\WxCircle;
use Dcat\Admin\Actions\Action;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Metrics\Card;
use Illuminate\Support\Facades\Cache;

class WxPostController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WxPost(['tags']), function (Grid $grid) {
            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $grid->model()->where('tenant_id', '=', $__MINI_GLOBAL_TENANT_ID__);
            }
            $grid->simplePaginate();
            $grid->quickSearch(['id', 'posts_content','user_id','user.user_name', 'circle_name'])->placeholder('搜索文章ID，内容，用户ID，用户名字，圈子名字...')->width(50);

            $grid->model()->orderBy('is_sticky', 'desc');
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id')->sortable();
            $grid->column('is_sticky')->using([0 => '否', 1 => '↑'])->label([
                0 => 'white',
                1 => 'red'
            ])->sortable();
            $grid->column('users', '头像')->display(function ($v) {
                return '<img src="' . ($this->user['user_avatar'] ?? Settings::get('img_default', 'https://img.mini.minisns.cn/icons/dafault.png'))  . '"  style="border-radius:50px;width:30px;" />';
            })->width('50px');
            $grid->column('user')->display(function ($v) {
                if($v && $v['user_name']){
                    return '<a target="_blank" href="'.admin_url('/users?id='.$v['id']).'">'.$v['user_name'].'</a>' ?? '用户已删除';
                }
                return '用户已删除';
            })->width('100px');
            $grid->column('posts_content')->display('更多') // 设置按钮名称
            ->expand(function ($a) {
                $content = _mini_phone(_mini_aite_replace(_mini_emoji($this->posts_content, true), true), true);
                $images = $this->images_url;
                if($images){
                    $images = Utils::imgWithStyle($images, 0, true);
                }
                $address = $this->address;
                $tagIds = WxPostsTag::where('posts_id', $this->id)->pluck('tags_id');
//                dump($tagIds);
                $tags = WxTag::whereIn('id', $tagIds)->get();
                $video = WxPostsVideo::where('posts_id', $this->id)->first();
                // 只填充内容，不需要标题
                $card = Card::make(view('admin/posts/detail', compact('content', 'images', 'address', 'tags', 'video')));
                return $card;

            })->width('150px');
            $grid->column('pay_content_id')->display(function ($v){
                if(_empty_($v)){
                    return '';
                }
                return '<a target="_blank" href="'.admin_url('posts/paycontent?id='.$v).'">付费内容</a>';
            });

//            $grid->column('images_url')->display(function ($pictures) {
//
//                return $pictures;
//
//            })->image('',200,90);
//            $grid->column('circle_id');

            $grid->column('circle_name');
            $grid->column('is_anonymous')->display(function ($v){
                if($v == 1){
                    return '是';
                }else{
                    return '';
                }
            });
//            $grid->column('tags')->display(function($v){
//                return $this->id;
//            });
//            $grid->column('address_id');
//            $grid->column('tags_id');
//            $grid->column('is_information')->select([0=>'否',1=>'是']);
            $grid->column('is_information')->switch()->sortable();
            $grid->column('is_examine')->using([0 => '待审核', 1 => '审核通过', 2 => '驳回'])->label([
                0 => 'red',
                1 => 'green',
                2 => 'default'
            ])->sortable();
//            $grid->column('overrule_content');
//            $grid->column('overrule_is_read');
            $grid->column('posts_state')->using([0 => '推送中', 1 => '用户删除', 2 => '已下架'])->label([
                0 => 'primary',
                1 => 'red',
                2 => 'default'
            ])->sortable();
            $grid->column('created_at');
//            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->equal('user_id');
                $filter->equal('circle_id')->select(WxCircle::pluck('circle_name', 'id'));
                $filter->equal('is_information')->select([0 => '否', 1 => '是']);
                $filter->equal('is_examine')->select([0 => '待审核', 1 => '审核通过', 2 => '驳回']);
                $filter->between('created_at')->date();
            });
            // 或
            $grid->batchActions(function ($batch) {
                $batch->add(new PostPassAction());
                $batch->add(new PostTopAction());
                $batch->add(new PostUnTopAction());
                $batch->add(new PostPushAction());
                $batch->add(new PostShelvesAction());
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append((new PostsAction())->setKey($this->id));
                $actions->append((new PostMetaAction())->setKey($this->id));
                $actions->append((new PostCommentLotteryAction())->setKey($this->id));
            });

            $grid->disableCreateButton();
//            $grid->disableActions();
            // 禁用编辑按钮
//            $grid->disableEditButton();
            // 禁用详情按钮
            $grid->disableViewButton();

            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $grid->tools([
                    new CommentManualButton(),
                ]);
            }
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxPost(), function (Show $show) {
            $show->field('id');
            $show->field('posts_content');
            $show->field('user_id');
            $show->field('circle_id');
            $show->field('circle_name');
            $show->field('address_id');
            $show->field('tags_id', '话题id(预留都为0)');
            $show->field('is_information');
            $show->field('is_examine');
            $show->field('overrule_content');
            $show->field('overrule_is_read');
            $show->field('posts_state');
            $show->field('tenant_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WxPost(), function (Form $form) {
            $form->display('id');
            if(($form->model()->img_count) > 0){
                UpdatePostImgCountJob::dispatch(($form->model()->id), 0, 0)->delay(now()->addSeconds(10));
            }

            if(__system_is_model_enable('laradocs', 'dcat-neditor')){
                $form->neditor('posts_content');
            }else{
                $form->editor('posts_content');
            }

//            $form->multipleSelectTable('user_id', '用户')
//                ->title('用户')
//                ->max(2)
//                ->from(UsersRender::make())
//                ->model(WxUser::class, 'id', 'user_name')->saving(function ($v) {
//                    if(is_array($v) && count($v) > 0){
//                        return $v[0];
//                    }else if(is_numeric($v)){
//                        return $v;
//                    }
//                    return 0;
//                })->required();

            $form->select('user_id', '用户')->options(function ($id) {
                $user = \App\Models\User\WxUser::find($id);
                if ($user) {
                    return [$user->id => $user->user_name];
                }
            })->ajax('select/users');

//            $form->text('circle_id');
            $form->select('circle_id','圈子ID')
                ->options(WxCircle::pluck('circle_name','id'));

//            $form->text('circle_name');
            $form->select('circle_name','圈子名称')
                ->options(WxCircle::pluck('circle_name','circle_name'));

//            $form->text('address_id');
            $form->select('address_id','位置')
                ->options(WxPostsAddress::pluck('address_name','id'));

//            $form->text('tags_id');
            $form->display('tags_id','话题id');

            $form->text('voter_id')->help('暂时通过修改这里，来和选票活动关联');

            $form->switch('is_information');

//            $form->text('is_examine');
            $form->radio('is_examine', '审核状态')->options([0=>'审核中',
                1=>'审核通过',
                2=>'驳回']);

            $form->text('overrule_content');

//            $form->text('overrule_is_read');
            $form->radio('overrule_is_read', '驳回用户是否已读')->options([0=>'未读',
                1=>'已读']);

//            $form->text('posts_state');
            $form->radio('posts_state', '状态')->options([0=>'正常',
                1=>'用户删除',2=>'管理员下架']);

            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $form->text('tenant_id', '本站分应用id')->help('忽略这个配置')->default($__MINI_GLOBAL_TENANT_ID__);
            }

            $form->saving(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                $form->tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                if(!_empty_($form->input('posts_content'))){
                    $form->posts_content = PostUtils::post_icon_inline_process($form->input('posts_content'));
                }
            });

            $form->saved(function (Form $form){
                Cache::forget('posts:post_type:'.($form->model()->id));
                Cache::forget('get_the_title:'.($form->model()->id).':30');
                Cache::forget('get_the_title:'.($form->model()->id).':15');
                Cache::forget('get_the_title:'.($form->model()->id).':100');
                Cache::forget('get:post:goods:'.($form->model()->id));
                Cache::forget('get:post:tags:'.($form->model()->id));
                Cache::forget('get:post:files:'.($form->model()->id));
                Cache::forget('get:post:sounds:'.($form->model()->id));

                \App\Models\Posts\WxPost::withoutSyncingToSearch(function () use (&$form){
                    \App\Models\Posts\WxPost::where('id', $form->model()->id )->update(['is_only_text'=>null]);
                });
                UpdatePostOnlyTextJob::dispatch($form->model()->id);

            });


            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    if(\App\Models\Posts\WxPost::where('id', $form->getKey())->value('tenant_id') != $__MINI_GLOBAL_TENANT_ID__){
                        return $form->response()->error('权限不足，不可以删除其他分站对象');
                    }
                }
            });

        });
    }
}
